<template>
  <div class="muzi muzi-form">
    <el-form :model="form" :rules="rules" ref="FormHandle" v-loading="show.loading" label-width="125px">
      <muzi-divide name="员工信息"/>
      <el-row :gutter="5">
        <el-col :span="8">
          <el-form-item label="姓名" prop="name" required>
            <el-autocomplete v-model="form.name" :fetch-suggestions="onFilter" placeholder="请输入关键字" @select="onSelected" highlight-first-item/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证件号码" prop="identity" required>
            <el-input v-model="form.identity" maxlength="18" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="日期" prop="ym" required>
            <el-date-picker v-model="form.ym" type="month" style="width: 100%" @change="onChangeMonth"/>
          </el-form-item>
        </el-col>
      </el-row>

      <muzi-divide name="项目信息"/>
      <el-row :gutter="5">
        <el-col :span="8">
          <el-form-item label="客户" prop="clienteleId" required>
            <el-select v-model="form.clienteleId" placeholder="请选择客户" @change="onClientele">
              <el-option v-for="item in options.clienteleList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目" prop="projectId" required>
            <el-select v-model="form.projectId" placeholder="请选择项目" @change="onProject">
              <el-option v-for="item in options.projectList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="options.teamList.length > 0">
          <el-form-item label="班组" prop="teamId" required>
            <el-select v-model="form.teamId" placeholder="请选择班组">
              <el-option v-for="item in options.teamList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <muzi-divide name="工资信息"/>
      <el-row :gutter="5">
        <el-col :span="8">
          <el-form-item label="本期收入" prop="total" required>
            <el-input v-model="form.total" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本期免税收入" prop="free">
            <el-input v-model="form.free" type="number" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="应缴个税" prop="tax">
            <el-input v-model="form.tax" type="number" disabled>
              <template #append>
                <el-button icon="el-icon-histogram" @click="onTaxCalculate"/>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="个税调整" prop="taxAdjust">
            <el-input v-model="form.taxAdjust" type="number" disabled>
              <template #append>
                <el-button icon="el-icon-histogram" @click="onTaxCalculate"/>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <muzi-divide name="专项扣除项"/>
      <el-row :gutter="5">
        <el-col :span="8">
          <el-form-item label="养老保险" prop="endowment">
            <el-input v-model="form.endowment" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="医疗保险" prop="medical">
            <el-input v-model="form.medical" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="失业保险" prop="unemployment">
            <el-input v-model="form.unemployment" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="住房公积金" prop="accumulation">
            <el-input v-model="form.accumulation" type="number" clearable/>
          </el-form-item>
        </el-col>
      </el-row>

      <muzi-divide name="专项附加扣除项"/>
      <el-row :gutter="5">
        <el-col :span="8">
          <el-form-item label="赡养老人费" prop="elderly">
            <el-input v-model="form.elderly" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="子女教育" prop="children">
            <el-input v-model="form.children" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="子女教育" prop="continuing">
            <el-input v-model="form.continuing" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="住房租金" prop="rent">
            <el-input v-model="form.rent" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="住房贷款利息" prop="loans">
            <el-input v-model="form.loans" type="number" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="其他" prop="other">
            <el-input v-model="form.other" type="number" clearable/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row class="operating" :gutter="5">
      <el-col :offset="19" :span="5">
        <el-button type="primary" size="large" :loading="show.saving" @click="onSubmit()">保存</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { dayjs } from "element-plus";

const DefaultValue = {
  // 专项扣除项
  medical: 0.0,
  endowment: 0.0,
  unemployment: 0.0,
  accumulation: 0.0, // 住房公积金

  // 专项附加扣除项
  children: 0.0,
  continuing: 0.0,
  loans: 0.0,
  rent: 0.0,
  elderly: 0.0,
  other: 0.0
}

export default {

  data() {
    return {
      form: {
        ...DefaultValue,
        ym: '' // 中间变量，提交时需删除
      },
      rules: {},
      show: {
        saving: false,
        loading: false,
      },
      options: {
        teamList: [],
        projectList: [],
        clienteleList: [],
      },
    }
  },
  mounted() {
    const {id} = this.$route.query;
    if (id) this.$API.salary.detail.get(id).then(res => {
      if (res.success) {
        this.form = res.data
        this.initForm();
        this.onClientele(this.form.clienteleId)
            .then(() =>  this.onProject(this.form.projectId)) // 解决联动回显问题
      }
    })

    // 初始化客户列表
    this.$API.clientele.list.get().then(res => {
      if (res.success) this.options.clienteleList = res.data;
    })
  },
  methods: {
    onSubmit() {
      this.$refs.FormHandle.validate(async (valid) => {
        if (valid) {
          this.show.saving = true;
          delete this.form.ym;
          let res = await this.$API.salary.create.post(this.form);
          this.show.saving = false;
          if (res.success) {
            this.$message.success("保存成功")
            this.$router.push({name: "salary", replace: true})
          } else {
            this.$alert(res.message, "提示", {type: 'error'})
          }
        }
      })
    },
    onChangeMonth(val) {
      const date = dayjs(val)
      this.form.year = date.year();
      this.form.month = date.month() + 1;
    },
    initForm() {
      const {year, month} = this.form;
      if (this.isBlank(year) || this.isBlank(month)) return;
      this.form.ym = `${year}-${month}`
    },
    isBlank(val) {
      return val === null || val === undefined || val === "";
    },
    onTaxCalculate() {
      console.info('实时计算个税')
    },
    onClientele(value) {
      return this.$API.project.list.get({id: value}).then(res => {
        if (res.success) {
          this.options.projectList = res.data;
          if (this.options.projectList.length === 0) {
            this.$message.warning("没有找到项目");
          }
        }
      });
    },
    onProject(value) {
      console.info('project id >>> ', value);
      console.info('project list >>>', this.options.projectList)
      const current = this.options.projectList.find(ele => ele.id === value);
      if (current.teamList.length > 0) this.options.teamList = current.teamList;
      else this.options.teamList = 0;
    },
    /**
     * 数据过滤
     * @param keyword
     * @param callback
     */
    onFilter(keyword, callback) {
      if (keyword === '') callback(Array.of());
      this.$API.employee.list.get({keyword}).then(res => {
        if (res.success) {
          const itemList = res.data.map(ele => ({value: ele.name, link: ele}))
          console.info(itemList)
          callback(itemList);
        }
      })
    },
    onSelected({link}) {
      const { name, type, identity, digest} = link;
      this.form = {
        name, type, identity, digest
      }
      this.defaultExemption(digest).then(res => console.info(res));
    },
    /**
     * 加载默认的附加扣除信息
     */
    defaultExemption(digest) {
      return this.$API.employee.exemption.detail.get(digest).then(res => {
        if (res.success) {
          const {
            medical, endowment, unemployment, accumulation, children, continuing, loans, rent, elderly, other
          } = res.data;
          this.form = {
            ...this.form, medical, endowment, unemployment, accumulation, children, continuing, loans, rent, elderly, other
          }
        }
      });
    }
  }
}
</script>

<style lang="less" scoped>
.muzi {
  .tax-date-editor-width {
    width: 100%;
  }

  .el-date-editor.el-input__wrapper {
    width: 100%;
  }
}
</style>
